﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using YXChatApiService.Core.Common;
using YXChatApiService.Repository;

namespace YXChatApiService.Core.BuddyEntity.DomainManager
{
    public class BuddyManager : DomainBaseManager<Buddy, Guid>, IBuddyManager
    {
        public BuddyManager(IRepository<Buddy, Guid> repository) : base(repository)
        {
        }

        public async Task<Buddy> InsertAsync(Buddy entity)
        {
            return await Repo.InsertAsync(entity);
        }

        public async Task DeleteAsync(Guid id)
        {
            var entity = QueryAsNoTracking.FirstOrDefault(n => n.Id == id);
            await Repo.DeleteAsync(entity);
        }

        public async Task<List<Buddy>> GetBuddyAll(string accountNumber)
        {
            var selfBuddy = await QueryAsNoTracking.Where(n =>
                    n.IsAgree &&
                    (n.AdderAccountNumber == accountNumber || n.AddeeAccountNumber == accountNumber))
                .ToListAsync();
            return selfBuddy;
        }

        public async Task<Buddy> GetBuddy(string adderNumber, string addeeNumber)
        {
            return await QueryAsNoTracking
                .FirstOrDefaultAsync(n =>
                    ((n.AdderAccountNumber == adderNumber && n.AddeeAccountNumber == addeeNumber)
                     || (n.AdderAccountNumber == addeeNumber && n.AddeeAccountNumber == adderNumber))
                    && n.IsAgree);
        }
        public async Task<Buddy> IsExistBuddy(string adderNumber, string addeeNumber)
        {
            return await QueryAsNoTracking
                .FirstOrDefaultAsync(n =>
                    (n.AdderAccountNumber == adderNumber && n.AddeeAccountNumber == addeeNumber)
                     || (n.AdderAccountNumber == addeeNumber && n.AddeeAccountNumber == adderNumber)
                    );
        }

        public async Task<bool> UpdateBuddy(Buddy entity)
        {
            var result= await Repo.UpdateAsync(entity);
            return result != null;
        }

        public async Task<Buddy> Get(Guid id)
        {
            return await QueryAsNoTracking.FirstOrDefaultAsync(n => n.Id == id);
        }
    }
}